import router from '@/router'
import { useLoginUserStore } from '@/stores/useLoginUserStore.ts'
import { message } from 'ant-design-vue'
import ACCESS_ENUM from '@/common/accessEnum.ts'

// 是否为首次获取登录用户
let firstFetchLoginUser = true

/**
 * 全局权限校验，每次切换页面都会执行
 */
router.beforeEach(async (to, from, next) => {
  const loginUserStore = useLoginUserStore()
  let loginUser = loginUserStore.loginUser
  // 确保页面刷新后，首次加载时，能等待后端返回用户信息后再校验权限
  if (firstFetchLoginUser) {
    await loginUserStore.fetchLoginUser()
    loginUser = loginUserStore.loginUser
    firstFetchLoginUser = false
  }
  const access = to.meta.access
  const role = loginUser?.userRole
  const isLogin = loginUser !== null && loginUser.userName !== '未登录' && role !== null
  if (access === ACCESS_ENUM.NOT_LOGIN) {
    next()
    return
  }
  if (isLogin) {
    if (access === ACCESS_ENUM.LOGIN) {
      next()
      return
    }
    if (access === role) {
      next()
      return
    } else {
      next('/access/NoAccess')
      return
    }
  } else {
    next('/user/login')
    return
  }
})
